package cn.icare.cms.controller;

import cn.icare.cms.ImageUtil;
import cn.icare.cms.ItemService;
import cn.icare.cms.dao.po.Member;
import cn.icare.cms.feignclients.UploadClient;
import cn.icare.cms.impl.AreaServiceImpl;
import cn.icare.cms.model.ro.ItemDetailVO;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import cn.icare.cms.qrcode.QRCodeUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/item")
@Api(tags = "REST商品")
public class ItemController extends BaseController {

    @Resource
    private ItemService itemService;
    @Autowired
    private UploadClient uploadClient;

    private final String FALL_STRING = "请求失败,服务繁忙!";

    private final Logger logger = LoggerFactory.getLogger(ItemController.class);


    /**
     * URL:http://{ip}:{port}/rest/itemcat?args={args}
     * method:GET
     *
     * @return
     */
    @GetMapping()
    @ApiOperation(value = "根据类别ID查询商品列表", notes = "根据类别ID查询商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "areaId", value = "区域Id", required = true, paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "cid", value = "商品分类Id", required = false, paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "name", value = "商品名称", required = false, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, defaultValue = "1", paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, defaultValue = "20", paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "isnew", value = "是否新品，1-新品", required = false, paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "isrecommend", value = "是否推荐，1-推荐商品", required = false, paramType = "query", dataTypeClass = Integer.class),
    })
    public ResponseEntity<RespMsgVO> getList(
            Long areaId,
            Long cid,
            String name,
            Integer pageNum,
            Integer pageSize,
            Integer isnew,
            Integer isrecommend
    ) {

        //TODO 第一版临时只有一个仓库的版本，以后多区域多仓库需要注释掉下面这行代码
        areaId = changeStoreAreaId(areaId);
        return super.getRespOk(this.itemService.getMiniList(areaId, cid, name
                , pageNum, pageSize, false, isnew, isrecommend));
    }


    /**
     * URL:http://{ip}:{port}/rest/item/{id}
     * method:GET
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    @ApiOperation(value = "查询单个商品详情信息", notes = "查询单个商品详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品Id", required = true, paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "areaId", value = "区域Id", required = true, paramType = "query", dataTypeClass = Long.class)

    })
    public ResponseEntity<RespMsgVO> getDetailOne(Long id,
                                                  Long areaId, HttpServletRequest request
    ) {
        //TODO 第一版临时只有一个仓库的版本，以后多区域多仓库需要注释掉下面这行代码
        Long memberId = 0L;
        Member member = this.getCurrentUser(request);

        if (member != null) {
            memberId = member.getId();
        }
        areaId = changeStoreAreaId(areaId);
        return super.getRespOk(this.itemService.getItemDetail(id, areaId, memberId));
    }


    @GetMapping("/hotlist")
    @ApiOperation(value = "根据类别ID查询热门商品列表", notes = "根据类别ID查询热门商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "areaId", value = "区域Id", required = true, paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "cid", value = "商品分类Id", required = false, paramType = "query", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, defaultValue = "1", paramType = "query", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true, defaultValue = "20", paramType = "query", dataTypeClass = Integer.class)
    })
    public ResponseEntity<RespMsgVO> getHotList(
            Long areaId,
            Long cid,
            Integer pageNum,
            Integer pageSize
    ) {

        //TODO 第一版临时只有一个仓库的版本，以后多区域多仓库需要注释掉下面这行代码
        areaId = changeStoreAreaId(areaId);
        return super.getRespOk(this.itemService.getMiniList(areaId, cid, ""
                , pageNum, pageSize, true, 0, 0));
    }

    /**
     * 商品主图与价格，合成一张图
     *
     * @throws IOException
     */
    @GetMapping("/getShareItemPic")
    @ApiOperation(value = "商品分享图片生成", notes = "商品分享图片生成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "picUrl", value = "商品图片Url", required = true, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orignPrice", value = "原价", required = false, paramType = "query", dataTypeClass = String.class),
            @ApiImplicitParam(name = "newPrice", value = "现价", required = true, defaultValue = "1", paramType = "query", dataTypeClass = String.class)
    })
    public ResponseEntity<RespMsgVO> getShareItemPic(String picUrl, String orignPrice, String newPrice
    ) {
        logger.warn("getShareItemPic:picUrl:"+picUrl+"-orignPrice:"+orignPrice+"-newPrice:"+newPrice);
        return uploadClient.getShareItemPic(picUrl, orignPrice, newPrice);
    }

    /**
     * 商品主图与价格，合成一张图
     *
     * @throws IOException
     */
    @GetMapping("/getShareItemPicNew")
    @ApiOperation(value = "商品分享图片生成-新接口", notes = "商品分享图片生成-新接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品Id", required = true, paramType = "query", dataTypeClass = Integer.class)

    })
    public ResponseEntity<RespMsgVO> getShareItemPicNew(Long id
    ) {

      ItemDetailVO detailVO= itemService.getShareItemDetail(id);
      if(detailVO==null)
      {
          return super.getRespFail("商品不存在或已经下架");

      }
      else {


          String picUrl=detailVO.getImage();
          String orignPrice="";
          String newPrice="";
          if(detailVO.getPromprice().compareTo(BigDecimal.valueOf(0))>0)
          {
              newPrice=detailVO.getPromprice().toString();
              orignPrice=detailVO.getPrice().toString();
          }
          else
          {
              newPrice=detailVO.getPrice().toString();
          }
          ResponseEntity<RespMsgVO> responseEntity= uploadClient.getShareItemPic(picUrl, orignPrice, newPrice);
          String imgUrl= responseEntity.getBody().getResData().toString();
          Map<String,String> map=new HashMap<>();
          map.put("title",detailVO.getTitle());
          map.put("pic",imgUrl);

          logger.warn("getShareItemPicNew:title:"+detailVO.getTitle()+"-pic:"+imgUrl+"-id:"+detailVO.getId());
          return super.getRespOk(map);
      }
    }


    //#region fallback methods

    //#endregion

}
